<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户组管理 - 名片管理系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 引入公共CSS -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <style>
        /* Reset and Base Styles */
        :root {
            --primary-color: #3498db;
            --primary-hover-color: #2980b9;
            --sidebar-bg: #2c3e50;
            --sidebar-text-color: #ecf0f1;
            --sidebar-active-link-bg: #34495e;
            --sidebar-active-link-border: var(--primary-color);
            --content-bg: #f4f6f9;
            --text-color: #333;
            --text-muted-color: #777;
            --card-bg: #ffffff;
            --card-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            --border-color: #e0e0e0;
            --success-color: #2ecc71;
            --error-color: #e74c3c;
            --font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: var(--font-family);
            background-color: var(--content-bg);
            color: var(--text-color);
            line-height: 1.6;
            display: flex;
        }

        a {
            text-decoration: none;
            color: var(--primary-color);
        }

        a:hover {
            color: var(--primary-hover-color);
        }

        /* Admin Container */
        .admin-container {
            display: flex;
            width: 100%;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 260px;
            background-color: var(--sidebar-bg);
            color: var(--sidebar-text-color);
            padding: 20px 0;
            display: flex;
            flex-direction: column;
            flex-shrink: 0;
        }

        .sidebar-title {
            font-size: 1.5em;
            font-weight: 600;
            text-align: center;
            padding: 0 20px 20px 20px;
            margin-bottom: 20px;
            border-bottom: 1px solid rgba(236, 240, 241, 0.1);
            color: var(--sidebar-text-color);
        }

        .menu-list {
            list-style-type: none;
        }

        .menu-item .menu-link {
            display: block;
            padding: 15px 25px;
            color: var(--sidebar-text-color);
            font-size: 1em;
            transition: background-color 0.3s ease, color 0.3s ease, border-left 0.3s ease;
            border-left: 3px solid transparent;
            text-decoration: none; /* 添加这行去除下划线 */
        }

        .menu-item .menu-link .fa {
            margin-right: 10px;
            width: 20px; /* Align icons */
            text-align: center;
        }

        .menu-item .menu-link:hover {
            background-color: var(--sidebar-active-link-bg);
            border-left-color: var(--primary-hover-color);
            color: #fff;
        }

        .menu-item .menu-link.active {
            background-color: var(--sidebar-active-link-bg);
            border-left-color: var(--sidebar-active-link-border);
            font-weight: 600;
            color: #fff;
        }

        /* Main Content */
        .main-content {
            flex-grow: 1;
            background-color: var(--content-bg);
            padding: 0;
            display: flex;
            flex-direction: column;
        }

        /* Header */
        .header {
            background-color: var(--card-bg);
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            border-bottom: 1px solid var(--border-color);
        }

        .header-title {
            font-size: 1.8em;
            font-weight: 600;
            color: var(--text-color);
        }

        .logout-button {
            background-color: var(--primary-color);
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            font-size: 0.9em;
            transition: background-color 0.3s ease;
            border: none;
            cursor: pointer;
            text-decoration: none;// 移除下划线
        }

        .logout-button:hover {
            background-color: var(--primary-hover-color);
            color: white;
        }

        .logout-button .fa {
            margin-right: 5px;
        }

        .table-actions {
            white-space: nowrap;
        }
        .modal-footer {
            display: flex;
            justify-content: space-between;
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <h2 class="sidebar-title">名片维护系统</h2>
            <ul class="menu-list">
                <li class="menu-item">
                    <a class="menu-link" href="/admin/index"><i class="fa fa-home"></i>首页</a>
                </li>
                <li class="menu-item">
                    <a class="menu-link" href="/admin/user-management"><i class="fa fa-users"></i>用户管理</a>
                </li>
                <li class="menu-item">
                    <a class="menu-link active" href="/admin/usergroup"><i class="fa fa-user-circle"></i>用户组管理</a>
                </li>
                <li class="menu-item">
                    <a class="menu-link" href="/admin/change-password"><i class="fa fa-key"></i>修改密码</a>
                </li>
            </ul>
        </div>

        <!-- 主要内容 -->
        <div class="main-content">
            <div class="header">
                <h2 class="header-title">用户组管理</h2>
                <a class="logout-button" href="/admin/logout"><i class="fa fa-sign-out"></i>退出登录</a>
            </div>

            <div class="content-area" style="padding: 30px;">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">用户组列表</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-primary" id="btnAddGroup">
                            <i class="fa fa-plus"></i> 新建用户组
                        </button>
                    </div>
                </div>

                <!-- 用户组列表 -->
                <div class="table-responsive">
                    <table id="groupTable" class="table table-striped table-sm">
                        <thead>
                            <tr>
                                <th data-field="id">ID</th>
                                <th data-field="groupName">用户组名称</th>
                                <th data-field="description">描述</th>
                                <th data-field="createTime" data-formatter="dateFormatter">创建时间</th>
                                <th data-field="operate" data-formatter="actionFormatter" class="table-actions">操作</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 用户组表单模态框 -->
    <div class="modal fade" id="groupModal" tabindex="-1" aria-labelledby="groupModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="groupModalLabel">新建用户组</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="groupForm">
                        <input type="hidden" id="groupId">
                        <div class="mb-3">
                            <label for="groupName" class="form-label">用户组名称</label>
                            <input type="text" class="form-control" id="groupName" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">描述</label>
                            <textarea class="form-control" id="description" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="btnSaveGroup">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 用户组成员管理模态框 -->
    <div class="modal fade" id="membersModal" tabindex="-1" aria-labelledby="membersModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="membersModalLabel">用户组成员管理</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="currentGroupId">
                    <div class="d-flex justify-content-between mb-3">
                        <h6>当前成员</h6>
                        <button type="button" class="btn btn-sm btn-primary" id="btnAddMember">
                            <i class="fa fa-plus"></i> 添加成员
                        </button>
                    </div>

                    <!-- 用户组成员列表 -->
                    <div class="table-responsive">
                        <table id="memberTable" class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th data-field="id">ID</th>
                                    <th data-field="username">用户名</th>
                                    <th data-field="realName">姓名</th>
                                    <th data-field="email">邮箱</th>
                                    <th data-field="actions" data-formatter="memberActionFormatter" class="table-actions">操作</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加成员模态框 -->
    <div class="modal fade" id="addMemberModal" tabindex="-1" aria-labelledby="addMemberModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addMemberModalLabel">添加用户组成员</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <!-- 可添加的用户列表 -->
                    <div class="table-responsive">
                        <table id="availableUserTable" class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th data-field="id">ID</th>
                                    <th data-field="username">用户名</th>
                                    <th data-field="realName">姓名</th>
                                    <th data-field="email">邮箱</th>
                                    <th data-field="actions" data-formatter="availableUserActionFormatter" class="table-actions">操作</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmDeleteModalLabel">确认删除</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>确定要删除这个用户组吗？此操作不可恢复。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="btnConfirmDelete">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入公共JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.16.0/locale/bootstrap-table-zh-CN.min.js"></script>

    <script>
        $(function() {
            // 添加AJAX全局错误处理
            $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
                console.error('AJAX错误:', {
                    url: ajaxSettings.url,
                    status: jqXHR.status,
                    statusText: jqXHR.statusText,
                    responseText: jqXHR.responseText
                });
                alert('请求失败: ' + jqXHR.status + ' ' + jqXHR.statusText);
            });

            // 初始化用户组表格
            $('#groupTable').bootstrapTable({
                url: '/admin/usergroup/list',
                method: 'get',
                pagination: true,
                sidePagination: 'client',
                pageSize: 10,
                pageList: [10, 25, 50, 100],
                search: true,
                showRefresh: true,
                locale: 'zh-CN',
                formatNoMatches: function() {
                    return '没有找到匹配的记录';
                },
                responseHandler: function(res) {
                    console.log('API返回数据:', res);
                    if (res.success && res.data) {
                        return res.data;
                    } else {
                        return [];
                    }
                },
                onLoadSuccess: function(data) {
                    console.log('表格加载成功，数据:', data);
                },
                onLoadError: function(status, res) {
                    console.error('表格加载失败:', status, res);
                    alert('加载用户组数据失败');
                }
            });

            // 打开新建用户组模态框
            $('#btnAddGroup').click(function() {
                $('#groupModalLabel').text('新建用户组');
                $('#groupId').val('');
                $('#groupName').val('');
                $('#description').val('');
                $('#groupModal').modal('show');
            });

            // 保存用户组
            $('#btnSaveGroup').click(function() {
                const id = $('#groupId').val();
                const groupName = $('#groupName').val();
                const description = $('#description').val();

                if (!groupName) {
                    alert('请输入用户组名称');
                    return;
                }

                const group = {
                    groupName: groupName,
                    description: description
                };

                let url = '/admin/usergroup/create';
                let method = 'POST';

                if (id) {
                    url = '/admin/usergroup/update';
                    group.id = id;
                }

                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(group),
                    success: function(response) {
                        if (response.success) {
                            $('#groupModal').modal('hide');
                            $('#groupTable').bootstrapTable('refresh');
                        } else {
                            alert(response.message || '操作失败');
                        }
                    },
                    error: function() {
                        alert('系统错误，请稍后再试');
                    }
                });
            });

            // 处理删除确认
            let deleteGroupId = null;
            $('#btnConfirmDelete').click(function() {
                if (deleteGroupId) {
                    $.ajax({
                        url: '/admin/usergroup/delete/' + deleteGroupId,
                        type: 'POST',
                        success: function(response) {
                            if (response.success) {
                                $('#confirmDeleteModal').modal('hide');
                                $('#groupTable').bootstrapTable('refresh');
                            } else {
                                alert(response.message || '删除失败');
                            }
                        },
                        error: function() {
                            alert('系统错误，请稍后再试');
                        }
                    });
                }
            });

            // 打开成员管理模态框
            $(document).on('click', '.btn-members', function() {
                const groupId = $(this).data('id');
                $('#currentGroupId').val(groupId);
                $('#membersModalLabel').text('用户组成员管理 - ' + $(this).data('name'));

                // 初始化成员表格
                $('#memberTable').bootstrapTable('destroy').bootstrapTable({
                    url: '/admin/usergroup/' + groupId + '/members',
                    method: 'get',
                    pagination: true,
                    sidePagination: 'client',
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    search: true,
                    locale: 'zh-CN',
                    formatNoMatches: function() {
                        return '没有找到匹配的记录';
                    },
                    responseHandler: function(res) {
                        if (res.success) {
                            return res.data;
                        } else {
                            return [];
                        }
                    }
                });

                $('#membersModal').modal('show');
            });

            // 打开添加成员模态框
            $('#btnAddMember').click(function() {
                const groupId = $('#currentGroupId').val();

                // 初始化可添加用户表格
                $('#availableUserTable').bootstrapTable('destroy').bootstrapTable({
                    url: '/admin/usergroup/' + groupId + '/availableUsers',
                    method: 'get',
                    pagination: true,
                    sidePagination: 'client',
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    search: true,
                    locale: 'zh-CN',
                    formatNoMatches: function() {
                        return '没有找到匹配的记录';
                    },
                    responseHandler: function(res) {
                        if (res.success) {
                            return res.data;
                        } else {
                            return [];
                        }
                    }
                });

                $('#addMemberModal').modal('show');
            });

            // 添加用户到用户组
            $(document).on('click', '.btn-add-to-group', function() {
                const groupId = $('#currentGroupId').val();
                const userId = $(this).data('id');

                $.ajax({
                    url: '/admin/usergroup/' + groupId + '/addUser/' + userId,
                    type: 'POST',
                    success: function(response) {
                        if (response.success) {
                            // 刷新两个表格
                            $('#availableUserTable').bootstrapTable('refresh');
                            $('#memberTable').bootstrapTable('refresh');
                        } else {
                            alert(response.message || '添加失败');
                        }
                    },
                    error: function() {
                        alert('系统错误，请稍后再试');
                    }
                });
            });

            // 从用户组移除用户
            $(document).on('click', '.btn-remove-from-group', function() {
                const groupId = $('#currentGroupId').val();
                const userId = $(this).data('id');

                $.ajax({
                    url: '/admin/usergroup/' + groupId + '/removeUser/' + userId,
                    type: 'POST',
                    success: function(response) {
                        if (response.success) {
                            // 刷新成员表格
                            $('#memberTable').bootstrapTable('refresh');
                        } else {
                            alert(response.message || '移除失败');
                        }
                    },
                    error: function() {
                        alert('系统错误，请稍后再试');
                    }
                });
            });

            // 编辑用户组事件委托
            $(document).on('click', '.btn-edit', function() {
                const id = $(this).data('id');
                const name = $(this).data('name');
                const description = $(this).data('description');
                editGroup(id, name, description);
            });

            // 删除用户组事件委托
            $(document).on('click', '.btn-delete', function() {
                const id = $(this).data('id');
                deleteGroup(id);
            });
        });

        // 日期格式化
        function dateFormatter(value) {
            if (!value) return '';
            const date = new Date(value);
            return date.toLocaleString();
        }

        // 用户组操作按钮格式化
        function actionFormatter(value, row) {
            console.log('格式化行数据:', row);
            return [
                '<div class="btn-group" role="group">',
                '<button type="button" class="btn btn-sm btn-info btn-members" data-id="' + row.id + '" data-name="' + row.groupName + '">',
                '<i class="fa fa-users"></i> 成员',
                '</button>',
                '<button type="button" class="btn btn-sm btn-warning btn-edit" data-id="' + row.id + '" data-name="' + row.groupName + '" data-description="' + (row.description || '') + '">',
                '<i class="fa fa-edit"></i> 编辑',
                '</button>',
                '<button type="button" class="btn btn-sm btn-danger btn-delete" data-id="' + row.id + '">',
                '<i class="fa fa-trash"></i> 删除',
                '</button>',
                '</div>'
            ].join('');
        }

        // 成员操作按钮格式化
        function memberActionFormatter(value, row) {
            return [
                '<button type="button" class="btn btn-sm btn-danger btn-remove-from-group" data-id="' + row.id + '">',
                '<i class="fa fa-times"></i> 移除',
                '</button>'
            ].join('');
        }

        // 可添加用户操作按钮格式化
        function availableUserActionFormatter(value, row) {
            return [
                '<button type="button" class="btn btn-sm btn-success btn-add-to-group" data-id="' + row.id + '">',
                '<i class="fa fa-plus"></i> 添加',
                '</button>'
            ].join('');
        }

        // 编辑用户组
        function editGroup(id, name, description) {
            $('#groupModalLabel').text('编辑用户组');
            $('#groupId').val(id);
            $('#groupName').val(name);
            $('#description').val(description);
            $('#groupModal').modal('show');
        }

        // 删除用户组
        function deleteGroup(id) {
            deleteGroupId = id;
            $('#confirmDeleteModal').modal('show');
        }
    </script>
</body>
</html>
